<?php
// components/WebUser.php
namespace app\components;

use Yii;
use yii\web\User;

class WebUser extends User
{
    public function beforeLogin($identity, $cookieBased, $duration)
    {
        // 自动登录的特殊处理
        if ($cookieBased) {
            // 检查最后活动时间是否超过5分钟
            if (!$identity->getIsActive()) {
                return $identity->beforeLogin(true); // 标记为自动登录
            }
            return true; // 允许自动登录
        }
        
        // 正常登录流程
        if ($identity->auth_key && $identity->auth_key != Yii::$app->session->get('user_auth_key')) {
            if (!$identity->getIsActive()) {
                return $identity->beforeLogin();
            }
            Yii::$app->session->setFlash('error', '该用户已在其他地方登录');
            return false;
        }
        
        return $identity->beforeLogin();
    }

    public function afterLogin($identity, $cookieBased, $duration)
    {
        parent::afterLogin($identity, $cookieBased, $duration);
        if (!$cookieBased) {
            Yii::$app->session->set('user_auth_key', $identity->auth_key);
        }
    }

    public function logout($destroySession = true)
    {
        $identity = $this->getIdentity();
        if ($identity !== null) {
           $identity->afterLogout();
            // 清除会话数据
            if($destroySession) Yii::$app->session->remove('user_auth_key');
        }
        
        return parent::logout();
    }    
  
}